<template>
  <div class="satisfied">
    <Affix :label="$t('configLazyLoad.channel.webchatSatisfiedConfig')" class="affix_tit">
      <div class = "header">
        <el-button class = "iconfont icon-zhankai"
                   @click = "addTag"><span>{{$t('configLazyLoad.channel.addLimit5')}}</span></el-button>
        <el-button class = "iconfont icon-shuaxin"
                   :loading = "refreshLoading"
                   @click = "refresh"><span>{{$t('public.refresh')}}</span></el-button>
      </div>
      <div class="border1">
        <!-- 无评价的提示 -->
        <div class="footer" v-show = "CSRDic.length === 0">{{$t('configLazyLoad.channel.webchatSatisfiedSet')}}</div>
        <!-- draggable可拖拽的包裹 github地址  https://github.com/SortableJS/Vue.Draggable
             :list 绑定可拖拽的数组
             :options 为拖拽的配置，当前组件只是设置了指定的拖拽元素,详情 https://github.com/RubaXa/Sortable#options
         -->
        <draggable class="list-group"
                   :options="dragOptions"
                   :list="CSRDic">
          <div v-for="(item, index) in CSRDic" class="drag" :key="index">
            <div class="item sdsd">
              <!-- 设置拖动的元素 透明度为0 占位 -->
              <div class="move">{{$t('configLazyLoad.channel.globalTip3')}}</div>
              <el-input v-model="item.name"
                        size="mini"
                        type="textarea"
                        :rows="2"
                        onkeydown="if(event.keyCode==13)return false;"
                        resize="none"
                        @blur = "isNull(index)"
                        :maxlength="50"
                        :placeholder = "item.nameTip ? item.nameTip : ''"></el-input>
            </div>
            <div class="tag_box">
              <div class="input_box">
                <el-input v-for="(i, index) in 6"
                          :key="index"
                          size="mini"
                          :maxlength="50"
                          type="textarea"
                          :rows="1"
                          onkeydown="if(event.keyCode==13)return false;"
                          resize="none"
                          v-model.trim="item.reason[i-1]"
                          :placeholder = "item.conten ? item.conten[i -1] : ''"
                          :class = "[index < 3 ? 'ipt' : '']"></el-input>
              </div>
              <div class="check_box">
                <div class="check_box_btn">
                  <el-checkbox class="" v-model="item.labelRequired">{{$t('configLazyLoad.channel.labelMustChoose')}}</el-checkbox>
                  <questionTooltip :tipContent="$t('configLazyLoad.channel.webchatSatisfieTitle1')" class="questionTootip"></questionTooltip>
                </div>
                <div class="check_box_btn">
                  <el-checkbox class="" v-model="item.proposalRequired">{{$t('configLazyLoad.channel.remarkMust')}}</el-checkbox>
                  <questionTooltip :tipContent="$t('configLazyLoad.channel.webchatSatisfieTitle2')" class="questionTootip"></questionTooltip>
                </div>
              </div>
            </div>
            <div class="item del">
              <span @click="del(index)" class="btn_del">{{$t('public.delete')}}</span>
            </div>
          </div>
        </draggable>
      </div>
    </Affix>

    <Affix :label="$t('configLazyLoad.channel.webchatSatisfieTitle3')" class="affix_tit">
      <el-form class="satisfaction_title_form" label-position="top" :model="formData" :rules="rules" ref="globaldata">
        <el-form-item :label="$t('configLazyLoad.channel.webchatSatisfieTitle13')" prop="satisfyTitle">
          <el-input type="textarea" :maxlength="120" :placeholder="$t('configLazyLoad.channel.webchatSatisfieTitle4')" v-model="formData.satisfyTitle"></el-input>
        </el-form-item>
        <el-form-item :label="$t('configLazyLoad.channel.webchatSatisfieTitle6')" prop="satisfyThank">
          <el-input type="textarea" :maxlength="120" :placeholder="$t('configLazyLoad.channel.webchatSatisfieTitle5')" v-model="formData.satisfyThank"></el-input>
        </el-form-item>
      </el-form>
    </Affix>
    <Affix :label="$t('configLazyLoad.channel.webchatSatisfieTitle7')" class="affix_tit" v-if="flag !== 'ecommerce'">
      <template slot="questionSlot">
        <questionTooltip :tipContent="$t('configLazyLoad.channel.webchatSatisfieTitle8')"></questionTooltip>
      </template>
      <el-radio-group class="radio-group" v-model="CSRAging">
        <el-radio :label="true">{{$t('public.yes')}}</el-radio>
        <el-radio :label="false">{{$t('public.no')}}</el-radio>
      </el-radio-group>
      <div v-show="CSRAging">
        <span style="margin-right: 10px;">{{$t('configLazyLoad.channel.webchatSatisfieTitle9')}}</span>
        <div class="CSR_timeOut">
          <el-input v-model.trim="CSRTimeOut" type="number" min="0" max="1440" @blur="blurMar('CSRTimeOut')" size="mini">
            <template slot="append">{{$t('public.minutes2')}}</template>
          </el-input>
        </div>
        <div class="prompt">{{$t('configLazyLoad.channel.webchatSatisfieTitle10')}}</div>
      </div>
    </Affix>
    <Affix :label="$t('configLazyLoad.channel.webchatSatisfiePushType')" class="affix_tit">
      <div class="forbidCheck"><el-checkbox class="" v-model="NotAllowAgentClosePushCsr">{{$t('configLazyLoad.channel.noCloseSessionPush')}}</el-checkbox></div>
      <div class="forbidCheck"><el-checkbox class="" v-model="NotAllowAgentPushCsr">{{$t('configLazyLoad.channel.noAgentPush')}}</el-checkbox></div>
      <div class="forbidCheck"><el-checkbox class="" v-model="NotAllowCustomerPushCsr">{{$t('configLazyLoad.channel.noVisitorsAppraise')}}</el-checkbox></div>
      <div class="forbidCheck" v-if="flag === 'kf'"><el-checkbox class="" v-model="NotAllowCustomerCloseCsr">禁止访客关闭会话窗口时弹出满意度评价（支持网站、iOS&Android SDK）</el-checkbox></div>
    </Affix>
    <Affix label="满意度评价结果是否展示给座席" class="affix_tit">
      <div class="forbidCheck">
        <el-radio-group class="radio-group" v-model="CSRShowToAgent">
          <el-radio label="all">展示满意度评价具体内容</el-radio>
          <el-radio label="part">仅展示访客是否完成评价</el-radio>
         </el-radio-group>
      </div>
    </Affix>
    <div class="wrap-save">
      <el-button type = "primary"  @click = "save" class = "save primary_btn fr">{{$t('public.save')}}</el-button>
    </div>
  </div>
</template>
<script>
  import draggable from 'vuedraggable'
  import {deepClone} from '@/utils/m7Utils'
  import Affix from '@/components/ui-modules/affix/Affix'
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  import * as uuid from 'uuid'
  export default {
    data () {
      return {
        CSRDic: [],
        refreshLoading: false,
        CSRAging: false,
        CSRShowToAgent: 'all',
        CSRTimeOut: 3,
        formData: {
          satisfyTitle: this.$t('configLazyLoad.channel.webchatSatisfieTitle11'),
          satisfyThank: this.$t('configLazyLoad.channel.webchatSatisfieTitle12')
        },
        NotAllowAgentClosePushCsr: false,
        NotAllowAgentPushCsr: false,
        NotAllowCustomerPushCsr: false,
        NotAllowCustomerCloseCsr: false,
        _id: '',
        rules: {
          satisfyTitle: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ],
          satisfyThank: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf'
      }
    },
    methods: {
      // 选项名称失去焦点触发的事件
      isNull (index) {
        if (!this.CSRDic[index].name) {
          this.$message.error(this.$t('configLazyLoad.channel.optionMustInput', {index: (index + 1)}))
        }
      },
      blurMar (type) {
        if (type === 'CSRTimeOut') {
          this.CSRTimeOut = parseInt(this.CSRTimeOut)
          if (!this.CSRTimeOut || this.CSRTimeOut < 1 || this.CSRTimeOut > 1440) {
            this.CSRTimeOut = 3
          }
        }
      },
      // 添加一个满意度
      addTag () {
        if (this.CSRDic.length === 5) {
          this.$message(this.$t('configLazyLoad.channel.limit5'))
          return
        }
        // 保证每个input都能绑定一个
        // reason, conten 保存时不需要传的数据, 目的只是为了渲染满意度配置项,保存时有处理
        let tag = {
          name: '',
          index: this.CSRDic.length,
          nameTip: this.$t('configLazyLoad.channel.example'),
          key: uuid.v1(),
          reason: ['', '', '', '', '', ''],
          conten: [
            this.$t('configLazyLoad.channel.exampl_1'),
            this.$t('configLazyLoad.channel.exampl_2'),
            this.$t('configLazyLoad.channel.exampl_3'),
            this.$t('configLazyLoad.channel.exampl_4'),
            this.$t('configLazyLoad.channel.exampl_5'),
            this.$t('configLazyLoad.channel.exampl_6')
            ],
          proposalRequired: false,
          labelRequired: false
        }
        this.CSRDic.push(tag)
      },
      refresh () {
        this.refreshLoading = true
        window.setTimeout(() => {
          this.refreshLoading = false
        }, 400)
        this.getView()
      },
      // 删除一个满意度
      del (index) {
        this.CSRDic.splice(index, 1)
      },
      // 获取满意度配置数据
      getView () {
        let data = {
          type: 'webchatCSR'
        }
        this.$store.dispatch('getCSRDic', data).then(res => {
          if (res && res.success && res.row) {
            this._id = res.row._id
            if (res.row.satisfyTitle !== undefined) {
              this.formData.satisfyTitle = deepClone(res.row.satisfyTitle)
            }
            if (res.row.satisfyThank !== undefined) {
              this.formData.satisfyThank = deepClone(res.row.satisfyThank)
            }
            this.CSRAging = res.row.CSRAging ? res.row.CSRAging : false
            if (res.row.timeout && res.row.timeout > 0 && res.row.timeout < 1441) {
              this.CSRTimeOut = res.row.timeout
            }
            this.CSRDic = this.inti(res.row.options)
            this.NotAllowAgentClosePushCsr = res.row.NotAllowAgentClosePushCsr || false
            this.NotAllowAgentPushCsr = res.row.NotAllowAgentPushCsr || false
            this.NotAllowCustomerPushCsr = res.row.NotAllowCustomerPushCsr || false
            this.NotAllowCustomerCloseCsr = res.row.NotAllowCustomerCloseCsr || false
            this.CSRShowToAgent = res.row.CSRShowToAgent || 'all'
          } else {
            this.CSRDic = []
          }
        })
      },
      // 初始化数据，保证每个input都会绑定一个数据
      inti (obj) {
        if (obj.length === 0) {
          return []
        }
        for (let j = 0; j < obj.length; j++) {
          for (let i = 0; i < 6; i++) {
            if (!obj[j].reason[i]) {
              obj[j].reason[i] = ''
            }
          }
          if (!obj[j].labelRequired) {
            this.$set(obj[j], 'labelRequired', false)
          }
          if (!obj[j].proposalRequired) {
            this.$set(obj[j], 'proposalRequired', false)
          }
        }
        return obj
      },
      // 保存满意度配置
      save () {
        let isName = true
        // 判断选项名是否为空
        this.CSRDic.map(item => {
          if (!item.name) {
            isName = false
          }
        })
        if (!isName) {
          this.$message.error(this.$t('configLazyLoad.channel.optionsMust'))
          return
        }
        var CSRClone = deepClone(this.CSRDic)
        var dataFlag = false
        for (let j = 0; j < CSRClone.length; j++) {
          var item = CSRClone[j]
          var _reason = []
          for (let i = 0; i < 6; i++) {
            if (item.reason[i].trim()) {
              _reason.push(item.reason[i])
            }
          }
          if (item.nameTip) {
            delete item.nameTip
          }
          if (item.conten) {
            delete item.conten
          }
          item.reason = _reason
          item.index = j
          //          如果开启了标签必选，那么标签就必须有值
          if (item.labelRequired && !item.reason.length) {
            dataFlag = true
            break
          }
        }
        if (dataFlag) {
          this.$message.error(this.$t('configLazyLoad.channel.LabelMustInput'))
          return
        }
        if (this.CSRAging && (this.CSRTimeOut < 1 || this.CSRTimeOut > 1440)) {
          this.$message.error(this.$t('configLazyLoad.channel.limit1to99'))
          return
        }
        let dataSave = {
          _id: this._id,
          type: 'webchatCSR',
          options: CSRClone,
          satisfyTitle: deepClone(this.formData.satisfyTitle),
          satisfyThank: deepClone(this.formData.satisfyThank),
          CSRAging: this.CSRAging,
          NotAllowAgentClosePushCsr: this.NotAllowAgentClosePushCsr,
          NotAllowAgentPushCsr: this.NotAllowAgentPushCsr,
          NotAllowCustomerPushCsr: this.NotAllowCustomerPushCsr,
          NotAllowCustomerCloseCsr: this.NotAllowCustomerCloseCsr,
          timeout: this.CSRTimeOut,
          CSRShowToAgent: this.CSRShowToAgent
        }
        this.$store.dispatch('saveCSRDic', dataSave).then(res => {
          if (res && res.success) {
            this.$message.success(this.$t('configLazyLoad.channel.setSuccess'))
          }
        })
      }
    },
    props: {
    },
    components: {
      draggable,
      questionTooltip,
      Affix
    },
    computed: {
      // 计算拖拽的配置
      dragOptions () {
        return {
          handle: '.move'
        }
      }
    },
    beforeMount () {
      this.getView()
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .satisfied
    overflow-y auto
    max-height 100%
    .footer
      height 60px
      text-align center
      line-height 60px
      font-size 16px
      border-bottom 1px solid $c-tree
    .header
      padding 6px 10px 6px 0
      height 34px
      line-height 34px
      .el-button
        margin-left 10px
      .icon-zhankai
        margin 0
      span
        cursor pointer
      .iconfont
        color $c-main
        font-size 12px
        border none
        padding 0
        span
          color $cf-gray2
          margin-left 6px
    .drag:nth-child(even)
    .drag:hover
      background $c-card
    .drag
      padding 10px 20px 10px 16px
      display flex
      align-items center
      position relative
      border-bottom 1px solid $c-tree
      .del
        width 8%
        text-align right
        color $c-pink
        position relative
        .btn_del
          cursor pointer
          position absolute
          right 0
      .sdsd
        width 20%
        .move
          position absolute
          width 100%
          height 100%
          opacity 0
          left 0
          top 0
          cursor move
      .tag_box
        display flex
        .input_box
          display inline-flex
          padding 0 20px
          flex-wrap wrap
          width 80%
        .el-textarea
          flex-basis 30%
          flex-grow 1
          padding 10px 10px 0 0
          flex-shrink 1
        .ipt
          padding-top 0
        .check_box
          display inline-flex
          flex-wrap wrap
          label
            flex-basis 100%
            flex-grow 1
            padding 8px 0
            flex-shrink 1
    .wrap-save
      height 30px
      padding 20px 20px
  .affix_tit
    width calc(100% - 80px)
    margin 40px auto 0
  .remark
    color: #888888
    font-size 12px
  .border1
    border 1px solid #ebebeb
  .check_box_btn
    position relative
  .questionTootip
    margin-left 10px
  .CSR_timeOut
    display inline-block
    width 150px
  .radio-group
    margin 10px 0 20px
  .prompt
    color $c-prompt
    line-height normal
    font-size 12px
    margin-top 10px
  .forbidCheck
    margin 10px 0
</style>
